<template>
  <div class="select-goods-container">
    <el-button
      type="primary"
      size="mini"
      plain
      :disabled="disabled"
      @click.stop="addProduct"
    >添加商品</el-button>
    <el-dialog
      title="选择商品库商品"
      :visible.sync="dialogVisible"
      width="70%"
      top="20px"
      custom-class="goods-select-dialog"
      append-to-body
    >
      <div class="content">
        <div class="left-box">
          <div class="category-type">
            <el-select
              v-model="categoryType"
              size="mini"
              placeholder="请选择"
              @change="categoryTypeChange"
            >
              <el-option
                v-for="item in categoryTypeMap"
                :key="item.value"
                :label="item.label"
                :value="item.value"
              />
            </el-select>
          </div>
          <div class="category-values">
            <div
              class="category-item"
              :class="{ selected: selectedCatId === 0 }"
              @click.stop="selectCategory(0)"
            >
              全部分类
            </div>
            <div
              v-for="(category, categoryIndex) in categorys"
              :key="categoryIndex"
              class="category-item"
              :class="{ selected: selectedCatId === category.cat_id }"
              @click.stop="selectCategory(category.cat_id)"
            >
              {{ category.cat_name }}
            </div>
          </div>
        </div>
        <div class="right-box">
          <div class="filter-box">
            <div class="filter-type">
              <el-select v-model="filterType" size="mini" placeholder="请选择搜索项">
                <el-option
                  v-for="item in filterMap"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value"
                />
              </el-select>
            </div>
            <div class="filter-value">
              <el-input
                v-model="filterKeyword"
                size="mini"
                placeholder="请输入搜索内容"
                clearable
                @change="filterKeywordChange"
              />
            </div>
            <el-button
              style="margin-left: 10px;"
              @click="resetFilter"
            >重置
            </el-button>
          </div>
          <div v-loading="listLoading" class="table-box" :class="{limited: limitNum > 0}">
            <el-table
              ref="multipleTable"
              :data="list"
              tooltip-effect="dark"
              style="width: 100%"
              header-cell-class-name="table-th"
              @select="handleSelectFunc"
              @select-all="handleSelectAllFunc"
              @selection-change="handleSelectionChange"
            >
              <el-table-column
                v-if="single"
                label="选择"
                align="center"
                width="55"
              >
                <template scope="scope">
                  <el-radio
                    v-model="radio"
                    :label="scope.row.product_id"
                    @change.native="getCurrentRow(scope.row)"
                  >{{ }}</el-radio>
                </template>
              </el-table-column>
              <el-table-column
                v-else
                type="selection"
                width="55"
                align="center"
                :selectable="goodSelectables"
              />
              <el-table-column
                label="商品名称"
                width="300"
                align="center"
                show-overflow-tooltip
              >
                <template slot-scope="scope">{{ scope.row.full_name }}</template>
              </el-table-column>
              <el-table-column
                prop="barcode"
                label="商品条码"
                width="200"
                align="center"
                show-overflow-tooltip
              />
              <el-table-column
                prop="quantity"
                label="门店库存"
                align="center"
                show-overflow-tooltip
              />
              <el-table-column
                prop="unit"
                label="单位"
                align="center"
                show-overflow-tooltip
              />
              <el-table-column v-if="isTransfer" prop="cost" label="采购价" align="center" />
              <el-table-column v-else prop="price" label="销售价格" align="center" />
            </el-table>
          </div>
          <div class="page-box">
            <pagination
              v-show="total > 0"
              layout="prev, pager, next"
              :total="total"
              :page.sync="filter.page"
              :limit.sync="filter.limit"
              @pagination="getGoodsList"
            />
          </div>
          <div class="btn-box">
            <div class="total-count">已选商品：{{ selectedCount }}</div>
            <el-button
              size="mini"
              type="primary"
              @click.stop="confirmSelected"
            >确定</el-button>
          </div>
        </div>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { getProducts, allCats, allHtcats } from '@/api/sell'
import Pagination from '@/components/Pagination'
const steamroller = function(list) {
  const result = []
  const getChildren = (arr) => {
    arr.forEach((v) => {
      if (v.children instanceof Array) {
        getChildren(v.children)
      } else {
        result.push(v)
      }
    })
  }
  getChildren(list)
  return result
}
export default {
  name: 'SelectGoods',
  components: { Pagination },
  filters: {},
  props: {
    selectedData: {
      required: true,
      type: Array,
      default() {
        return []
      }
    },
    selectedStore: {
      required: false,
      type: [Number, String],
      default: undefined
    },
    disabled: {
      type: Boolean,
      default() {
        return false
      }
    },
    storeDisabled: {
      type: Boolean,
      default() {
        return false
      }
    },
    single: {
      type: Boolean,
      default() {
        return false
      }
    },
    isTransfer: {
      type: Boolean,
      default() {
        return false
      }
    },
    limitNum: {
      required: false,
      type: [Number, String],
      default: undefined
    },
  },
  data() {
    return {
      listLoading: false,
      dialogVisible: false,
      categoryType: 'cat_id',
      categoryTypeMap: [
        { label: '商品分类', value: 'cat_id' },
        { label: '后台分类', value: 'htcat_id' }
      ],
      categorys: [],
      filterType: 'name',
      filterMap: [
        { label: '商品名称', value: 'name' },
        { label: '商品编号', value: 'bn' }
      ],
      filterKeyword: '',
      filter: {
        page: 1,
        limit: 10,
        store_id: undefined,
        type: 0
      },
      total: 0,
      list: [],
      multipleSelection: [],
      radio: '',
      newSelection: []
    }
  },
  computed: {
    selectedCatId: function() {
      const selectedIndex = this.categorys.findIndex(
        (category) => category.selected
      )
      return selectedIndex >= 0 ? this.categorys[selectedIndex].cat_id : 0
    },
    selectedCount: function() {
      return this.newSelection.length
    }
  },
  mounted() {
    if (this.selectedData.length > 0) {
      this.newSelection = this.selectedData
    }
  },
  methods: {
    addProduct() {
      this.filter = Object.assign({}, this.filter, { page: 1 })
      this.filter.store_id = this.selectedStore
      this.filter.type = this.storeDisabled ? 1 : 0
      this.list = []
      this.dialogVisible = true
      this.fetchCategory()
      this.getGoodsList()
    },
    handleSelectAllFunc(selection) {
      // 是否是全部取消操作，如果是则找出取消的行
      if (selection.length === 0) {
        this.list.forEach(deletedItem => {
          const deletedId = deletedItem.product_id
          const needDeleteId = this.newSelection.findIndex(item => item.product_id === deletedId)
          if (needDeleteId >= 0) {
            this.newSelection.splice(needDeleteId, 1)
          }
        })
      }
    },
    handleSelectFunc(selection, row) {
      // 是否是取消操作，如果是则找出取消的行
      if (!selection.some(selectItem => {
        return selectItem.product_id === row.product_id
      })) {
        const deletedId = row.product_id
        const needDeleteId = this.newSelection.findIndex(item => item.product_id === deletedId)
        if (needDeleteId >= 0) {
          this.newSelection.splice(needDeleteId, 1)
        }
      }
    },
    handleSelectionChange(val) {

      if (this.limitNum > 0 && this.newSelection.length >= this.limitNum) {
        this.newSelection = this.newSelection.slice(0, this.limitNum)
        this.multipleSelection = val.filter(ele=>{
          const cancelIndex = this.newSelection.findIndex(item => item.product_id === ele.product_id)
          if (cancelIndex < 0) {
            this.$refs.multipleTable.toggleRowSelection(ele, false)
            return false
          }
          return true
        })
        return
      }

      // 处理分页导致的选中丢失
      const newVal = val.filter(newVal => {
        const existIndex = this.newSelection.findIndex(item => item.product_id === newVal.product_id)
        return existIndex < 0
      })
      this.newSelection = this.newSelection.concat(newVal)
      this.multipleSelection = val
    },
    toggleSelection(rows) {
      this.$refs.multipleTable.clearSelection()
      if (rows) {
        rows.forEach((row) => {
          this.$refs.multipleTable.toggleRowSelection(row, true)
        })
      }
    },
    fetchCategory() {
      if (this.categoryType === 'cat_id') {
        allCats()
          .then((response) => {
            const { data } = response
            this.categorys = data
          })
          .catch(() => {})
      } else if (this.categoryType === 'htcat_id') {
        allHtcats()
          .then((response) => {
            const { data } = response
            this.categorys = steamroller(data)
          })
          .catch(() => {})
      }
    },
    categoryTypeChange(categoryType) {
      this.fetchCategory()
    },
    goodSelectables(row, index) {
      if (this.storeDisabled) {
        return row.quantity >= 1
      } else {
        return true
      }
    },
    getGoodsList() {
      this.filter[this.categoryType] = this.selectedCatId
      this.filter[this.filterType] = this.filterKeyword
      this.listLoading = true
      getProducts(this.filter).then((response) => {
        this.listLoading = false
        const { list, total } = response.data
        list.forEach(e => {
          e.quantity = e.store_goods[0] ? e.store_goods[0].quantity : 0
        })

        this.list = list
        this.total = total

        this.$nextTick(() => {
          const oldSelectedData = this.list.filter((listItem) => {
            // const oldSelectedIndex = this.selectedData.findIndex(
            //   (selectDataItem) =>
            //     selectDataItem.product_id === listItem.product_id
            // )
            const newSelectedIndex = this.newSelection.findIndex(
              (newSelectDataItem) =>
                newSelectDataItem.product_id === listItem.product_id
            )
            // return oldSelectedIndex >= 0 || newSelectedIndex >= 0
            return newSelectedIndex >= 0
          })
          this.toggleSelection(oldSelectedData)
        })
      })
    },
    selectCategory(catId) {
      const oldSelectIndex = this.categorys.findIndex(
        (category) => category.selected
      )
      if (oldSelectIndex >= 0) {
        this.$set(this.categorys[oldSelectIndex], 'selected', false)
      }
      if (catId > 0) {
        const selectIndex = this.categorys.findIndex(
          (category) => category.cat_id === catId
        )
        this.$set(this.categorys[selectIndex], 'selected', true)
      }
      this.$nextTick(() => {
        this.filter = Object.assign({}, this.filter, { page: 1 })
        this.getGoodsList()
      })
    },
    filterKeywordChange() {
      this.filter = Object.assign({}, this.filter, { page: 1 })
      this.getGoodsList()
    },
    confirmSelected() {
      this.$emit('selectedChange', this.newSelection)
      this.dialogVisible = false
    },
    getCurrentRow(row) {
      this.multipleSelection = [row]
      this.newSelection = [row]
    },
    resetFilter() {
      this.filterType = 'name'
      this.filterKeyword = ''
      this.filter = Object.assign({}, this.filter, { page: 1 })
      this.getGoodsList()
    }
  }
}
</script>

<style scoped lang="scss">
.goods-select-dialog {
  .content {
    display: flex;
    justify-content: center;
    align-items: flex-start;
    .left-box {
      flex: none;
      .category-values {
        padding: 10px 0;
        box-sizing: border-box;
        height: 500px;
        overflow-y: scroll;
        .category-item {
          display: flex;
          justify-content: center;
          align-items: center;
          height: 40px;
          &:hover {
            cursor: pointer;
          }
          &.selected {
            color: #1890ff;
          }
        }
      }
    }
    .right-box {
      flex: auto;
      width: 600px;
      padding-left: 10px;
      box-sizing: border-box;
      .filter-box {
        display: flex;
        justify-content: flex-end;
        align-items: center;
        .filter-type {
          margin-right: 10px;
        }
      }
      .table-box {
        margin-top: 10px;
        &.limited {
          ::v-deep .el-table__header-wrapper .el-checkbox {
            display: none;
          }
        }
      }
      .page-box {
        display: flex;
        justify-content: flex-end;
        align-items: center;
        .pagination-container {
          padding: 0;
        }
      }
      .btn-box {
        margin-top: 20px;
        display: flex;
        justify-content: center;
        align-items: center;
        .total-count {
          margin-right: 20px;
        }
      }
    }
  }
}
</style>
